appModule.service("terminalService", ["$ionicPopup", "sshClientService", "$rootScope", function($ionicPopup, sshClientService, $rootScope) {
    var service = {
        openTerminal: function(terminalDiv, sshSession) {
            // 添加当前会话
            $rootScope.sessions.push(sshSession);
            // 创建终端
            var terminal = service.createTerminal(terminalDiv, sshSession);
            terminal.pause();
            // 连接ssh server
            service.connectServer(terminalDiv, terminal, sshSession);
        },
        createTerminal: function(terminalDiv, sshSession) {
            return terminalDiv.terminal(function (command, term) {
                service.executeShell(terminalDiv, term, sshSession, command);
            }, {
                greetings: "正在初始化",
                name: sshSession.name,
                height: "100%",
                prompt: "连接到" + sshSession.sshSessionConfig.host + "..."
            });
        },
        connectServer: function(terminalDiv, terminal, sshSession) {
            sshClientService.connect(sshSession, function(serverResult) {
                service.callback(terminalDiv, terminal, sshSession, serverResult);
                terminal.resume();
            }, function () {
                service.failCallback(sshSession);
            });
        },
        executeShell: function (terminalDiv, terminal, sshSession, command) {
            var prompt = terminal.get_prompt();
            terminal.set_prompt("");
            sshClientService.execute(sshSession.id, command, function () {
            }, function () {
                terminal.set_prompt(prompt);
                service.failCallback(sshSession);
            });
        },
        failCallback: function(sshSession) {
            $ionicPopup.alert({title: "连接失败"});
            service.removeSession(sshSession);
            console.error("sshConnect.connect异常: " + JSON.stringify(arguments));
        },
        callback: function(terminalDiv, terminal, sshSession, serverResult) {
            console.debug("服务器响应: " + serverResult);
            terminal.echo(terminal.get_prompt());
            terminal.set_prompt(serverResult);
        },
        removeSession: function(session) {
            $.each($rootScope.sessions, function(i) {
                if(this.id == session.id) {
                    $rootScope.sessions.splice(i, 1);
                    $("#" + session.id).remove();

                    if($rootScope.sessions.length) {
                        $rootScope.$emit("changeTerminal", $rootScope.sessions[0]);
                    } else {
                        $rootScope.curSession = null;
                    }
                    return false;
                }
            });
        }
    };
    return service;
}]);